<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <div class="block">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader
          v-model="selectKeys"
          :options="parentAttrlist"
          :props="caseProps"
          @change="handleChange"
        ></el-cascader>
      </div>
      <el-tabs v-model="name" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="small"
            :disabled="isable"
            @click="addVisible = true"
            >添加参数</el-button
          >
          <el-table
            :data="dynamicList"
            style="width: 100%; margin-top: 15px"
            border
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removetags(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="small"
                    @click="showEdit(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="small"
                    @click="remoeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="isable"
            @click="addVisible = true"
            >添加属性</el-button
          >
          <el-table
            :data="OnlyList"
            style="width: 100%; margin-top: 15px"
            border
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removetags(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="small"
                    @click="showEdit(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="small"
                    @click="remoeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加数据弹框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑数据弹框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //下拉框选中的数据,双向绑定
      selectKeys: [],
      //下拉框的数据
      parentAttrlist: [],
      //指定级联选择器的配置对象
      caseProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //绑定被选中按钮的name值
      name: 'many',

      // 动态数据
      dynamicList: [],
      // 静态数据
      OnlyList: [],
      // 添加弹框显示隐藏
      addVisible: false,
      // 编辑弹框显示隐藏
      editVisible: false,
      // 添加表单的验证规则对象
      rules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 添加数据
      addForm: {
        attr_name: '',
      },
      // 编辑数据
      editForm: {},
    }
  },
  mounted() {
    this.getParentcatdialog()
  },
  methods: {
    // 获取添加下拉列表的数据
    async getParentcatdialog() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
      this.parentAttrlist = res.data
    },
    // 下拉选择项发生改变时触发
    handleChange() {
      this.getParamsData()
    },
    // 监听切换动静态时触发的事件
    handleClick() {
      this.getParamsData()
    },
    // 获取表格数据
    async getParamsData() {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        // 动态数据
        this.dynamicList = []
        // 静态数据
        this.OnlyList = []
        return
      }
      //发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes`,
        {
          params: { sel: this.name },
        }
      )
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制添加标签的切换
        item.inputVisible = false
        // 添加标签的值
        item.inputValue = ''
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取消息失败')
      if (this.name == 'many') {
        this.dynamicList = res.data
      } else {
        this.OnlyList = res.data
      }
    },
    // 监听添加对话框的重置事件
    addDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },

    // 添加数据
    addParams() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.selectKeys[2]}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.name,
          }
        )
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.getParamsData()
      })
      this.addVisible = false
    },
    //删除数据
    async remoeParams(id) {
      // console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户确认删除则返回字符串confirm,取消则返回cancel
      // console.log(confirmResult)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(
          `categories/${this.selectKeys[2]}/attributes/${id}`
        )
        if (res.meta.status !== 200) return this.$message.error('用户删除失败')
        // 删除成功重新渲染
        this.$message.success('删除用户成功！')
        this.getParamsData()
      } else {
        this.$message.info('已取消删除')
      }
    },
    //点击编辑显示弹框和信息
    async showEdit(id) {
      this.editVisible = true
      const {
        data: res,
      } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes/${id}`,
        { params: { sel: this.name } }
      )
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      this.editForm = res.data
    },
    // 修改数据
    editParams() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.selectKeys[2]}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.name,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('恭喜，修改成功')
        this.getParamsData()
      })
      this.editVisible = false
    },
    // 关闭 Tag 时触发的事件
    removetags(index, data) {
      data.attr_vals.splice(index, 1)
      this.getTages(data)
    },
    // 点击按钮显示文本框
    showInput(data) {
      data.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本失去焦点
    handleInputConfirm(data) {
      let inputValue = data.inputValue
      if (inputValue.trim().length !== 0) {
        data.attr_vals.push(inputValue)
        this.getTages(data)
      }
      data.inputVisible = false
      data.inputValue = ''
    },
    // 请求修改tage函数
    async getTages(data) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectKeys[2]}/attributes/${data.attr_id}`,
        {
          attr_name: data.attr_name,
          attr_sel: data.attr_sel,
          attr_vals: data.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
    },
  },
  computed: {
    isable() {
      if (this.selectKeys.length == 3) {
        return false
      } else {
        return true
      }
    },
    titleText() {
      if (this.name == 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    },
  },
}
</script>
<style lang="less" scoped>
.block {
  margin-top: 15px;
  margin-bottom: 15px;
}
.el-tag {
  margin: 0 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>